package com.cskaoyan.mall.controller.mall;

import com.cskaoyan.mall.model.bo.order.AddCartOrderBo;
import com.cskaoyan.mall.model.bo.order.CartListEntityBo;
import com.cskaoyan.mall.model.bo.order.CriticismBo;
import com.cskaoyan.mall.model.bo.order.SettleAcountsBo;
import com.cskaoyan.mall.model.po.Criticism;
import com.cskaoyan.mall.model.po.GoodsAndSpec;
import com.cskaoyan.mall.model.po.Order;
import com.cskaoyan.mall.model.po.User;
import com.cskaoyan.mall.model.vo.order.CartOrderVo;
import com.cskaoyan.mall.service.lmpl.OrderServiceImpl;
import com.cskaoyan.mall.service.lmpl.UserServiceImpl;
import com.cskaoyan.mall.utils.Json;
import com.cskaoyan.mall.utils.Result;
import com.google.gson.Gson;

import javax.print.attribute.standard.MediaSize;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @ClassName: MallOrderServlet
 * @Description: TODO
 * @Auther 庄左
 * @Date 2022/7/3 18:46
 * @Version
 **/
@WebServlet("/api/mall/order/*")
public class MallOrderServlet extends HttpServlet {

    private Json json = new Json();
    private Gson gson = new Gson();
    private Result result= new Result();
    private UserServiceImpl userService = new UserServiceImpl();
    private OrderServiceImpl orderService = new OrderServiceImpl();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String replace = requestURI.replace(req.getContextPath() + "/api/mall/order/", "");
        if("getOrderByState".equals(replace)){
            getOrderByState(req,resp);
        }
        if ("pay".equals(replace)){
            pay(req,resp);
        }
        if ("confirmReceive".equals(replace)){
            confirmRecevice(req,resp);
        }
        if("deleteOrder".equals(replace)){
            deleteOrder(req,resp);
        }

    }


    /**
    * @Author: 庄左
    * @Description: 根据订单id删除订单
    * @DateTime: 2022/7/9 16:06
    */
    private void deleteOrder(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        Integer id = Integer.valueOf(req.getParameter("id"));
        orderService.deleteOrder(id);

        result.setCode(0);
        resp.getWriter().println(gson.toJson(result));

    }





    /**
    * @Author: 庄左
    * @Description: 将订单状态改为收货
    * @DateTime: 2022/7/9 13:33
    */
    private void confirmRecevice(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        Integer id = Integer.valueOf(req.getParameter("id"));
        int i = orderService.updateOrderStateByOrderIdFromConfirmReceive(id);
        if (i==0){
            result.setCode(10000);
            result.setMessage("收货失败，请稍后重试");
            resp.getWriter().println(gson.toJson(result));
        }
        result.setCode(0);
        resp.getWriter().println(gson.toJson(result));
    }

    /**
* @Author: 庄左
* @Description: 将订单状态更改为已发货即可
 * 需要订单id
 * 更改状态id，状态名称
* @DateTime: 2022/7/8 13:32
*/
    private void pay(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer id = Integer.valueOf(req.getParameter("id"));
        orderService.updateOrderStateByOrderIdFromPay(id);

        result.setCode(0);
        resp.getWriter().println(gson.toJson(result));
    }

    /**
    * @Author: 庄左
    * @Description: 个人中心的购物车,订单展示，依据发货状态
    * @DateTime: 2022/7/3 18:51
    */
    private void getOrderByState(HttpServletRequest req, HttpServletResponse resp) throws IOException {


        //从session域中获取用户昵称
        String name = (String) req.getSession().getAttribute("name");
        //获取请求参数
        Integer state = Integer.valueOf(req.getParameter("state"));
        //根据state，用户昵称 查询订单，state=0即为 该用户 购物车中的商品
        // 利用OrderMapper中的selectCartOrderByStateId和selectCartGood来查询
        //创建OrderServiceImpl的对象

        List<CartOrderVo> cartOrderVos = orderService.selectCartOrderByStateId(state,name);

        result.setCode(0);
        result.setData(cartOrderVos);
        resp.getWriter().println(gson.toJson(result));

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String replace = requestURI.replace(req.getContextPath() + "/api/mall/order/", "");
        if ("addOrder".equals(replace)){
            addOrder(req,resp);
        }
        if("settleAccounts".equals(replace)){
            settleAccounts(req,resp);
        }
        if("sendComment".equals(replace)){
            sendComment(req,resp);
        }


    }


    /**
    * @Author: 庄左
    * @Description: 完成订单之后的评论，
     * 请求中有输入的评论内容，规格id,商品id，订单id，评分，用户昵称
     * 根据将这些内容写入评论表中，另外还需要直接写入时间，用户id-----根据用户昵称查找得到，规格名称---根据规格id查找得到，
    * @DateTime: 2022/7/8 16:51
    */
    private void sendComment(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        CriticismBo criticismBo = gson.fromJson(json.getJsonString(req), CriticismBo.class);

        int i = orderService.insertCriticsm(criticismBo);
        if(i==0){
            result.setCode(10000);
            result.setMessage("评论失败，请稍后再试");
        }else {
            //更新订单的hascomment
            orderService.updateOrderHasComment(criticismBo.getOrderId());

            result.setCode(0);
            resp.getWriter().println(gson.toJson(result));
        }


    }

    /**
* @Author: 庄左
* @Description: 一键下单，即将购物车中的订单状态由未付款改为未发货状态，只需遍历订单个数，将购物车中的订单，更改stateid和state即可
* @DateTime: 2022/7/7 18:58
*/
    private void settleAccounts(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        SettleAcountsBo settleAcountsBo = gson.fromJson(json.getJsonString(req), SettleAcountsBo.class);
        //一键全部下单
        orderService.updateOrderStateIdAndState();

        result.setCode(0);
        resp.getWriter().println(gson.toJson(result));
    }

    /**
    * @Author: 庄左
    * @Description: 加入购物车就是添加一个state=0，未付款的订单，
     * 请求报文提供amount，goodsDetailId，num,state(发货状态的id)，token（用户昵称）
    * @DateTime: 2022/7/4 16:05
    */
    private void addOrder(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        //获得请求体
        AddCartOrderBo addCartOrderBo = gson.fromJson(json.getJsonString(req), AddCartOrderBo.class);

        //根据规格id拿到 规格spec，商品id   商品数量
        // TODO：另外需要将该规格的商品数量与购买数量作比较，可以直接相减（商品数量-购买数量）结果大于0才可购买，差值将用于更新该规格的商品数量
        Integer specId = addCartOrderBo.getGoodsDetailId();
        GoodsAndSpec goodsAndSpec = orderService.selectGoodsIdAndSpecMessageBySpecId(specId);
        //取出库存值，购买数量
        Integer num = addCartOrderBo.getNum();
        Integer stockNum = Integer.valueOf(goodsAndSpec.getStockNum());

        if (stockNum-num<0){
            result.setCode(10000);
            result.setMessage("库存不足");
            resp.getWriter().println(gson.toJson(result));
            return;
        }
        //库存足够，计算购买后的库存
        stockNum=stockNum-num;

        //根据发货状态id，拿到发货状态stateValue
        Integer stateId = addCartOrderBo.getState();
        String state = orderService.selectStateValueByStateId(stateId);

        //根据商品id拿到商品的名称和图片 goods img
        Integer goodsId = goodsAndSpec.getGoodsid();
        GoodsAndSpec goodsAndSpec1 = orderService.selectGoodsMessageByGoodsId(goodsId);
        //根据昵称拿到用户的id，用户名，收件人，地址，电话
        String token = addCartOrderBo.getToken();
        User user = orderService.selectUserMessageByUserNickName(token);

        //手续办完 准备加入购物车
        orderService.insertGoodsToCart(addCartOrderBo,state,goodsAndSpec,goodsAndSpec1,user);

        //加入之后对相应的商品数量做一个更改,根据规格id找到库存
        //修改规格表的库存
        orderService.updateStockNumInSpec(stockNum,specId);

        result.setCode(0);
        resp.getWriter().println(gson.toJson(result));


    }
}
